import {
  registerDecorator,
  ValidationArguments,
  ValidationOptions,
  ValidatorConstraint,
  ValidatorConstraintInterface,
} from 'class-validator';

@ValidatorConstraint()
export class IsChineseIdCardConstraint implements ValidatorConstraintInterface {
  validate(idCard: string, args: ValidationArguments) {
    const regex =
      /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/;
    const validRes = regex.test(idCard);

    return validRes;
  }

  // defaultMessage(args: ValidationArguments) {
  //   return '身份证号码不合法';
  // }
}

export function IsChineseIdCard(validationOptions?: ValidationOptions) {
  return function (object: Object, propertyName: string) {
    registerDecorator({
      target: object.constructor,
      propertyName: propertyName,
      options: validationOptions,
      constraints: [],
      validator: IsChineseIdCardConstraint,
    });
  };
}
